package com.anjie.powerproject.service.impl;

import com.anjie.powerproject.common.MockDataUtil;
import com.anjie.powerproject.entity.PreDataDay;
import com.anjie.powerproject.repository.PreDataDayRepository;
import com.anjie.powerproject.service.PreDataDayService;
import com.anjie.powerproject.strategy.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PreDataDayServiceImpl implements PreDataDayService {

    @Autowired
    PreDataDayRepository preDataDayRepository;

    @Autowired
    MockDataUtil mockDataUtil;

    @Autowired
    Environment env;

    @Override
    public List<BigDecimal> getPreDataDayValueByCodeAndDateRange(List<String> dateList, String deviceCode, Integer model, Date startTime, Date endTime) {
        if (Arrays.asList(env.getActiveProfiles()).contains("dev")) {
            return getPreDataDayValueInDevEnv(dateList.size());
        }

        Date limitDate = DateUtils.plusOrMinusDay(endTime, 1).getTime();

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String start = dateFormat.format(startTime);
        String end = dateFormat.format(limitDate);

        List<PreDataDay> preDataDayValues = preDataDayRepository.getPreDataDayValues(deviceCode, model, start, end);

        Map<String, PreDataDay> preDataDayMap = preDataDayValues.stream().collect(Collectors.toMap(e -> dateFormat.format(e.getDate()), e -> e, (e1, e2) -> e1));
        List<PreDataDay> preDataDayList = new ArrayList<>();
        for (String date : dateList) {
            PreDataDay preDataDay = preDataDayMap.get(date);
            if (preDataDay == null) {
                preDataDay = new PreDataDay();
                preDataDay.setData(BigDecimal.valueOf(0.0));
            }
            preDataDayList.add(preDataDay);
        }

        return preDataDayList.stream().map(PreDataDay::getData).collect(Collectors.toList());
    }

    @Override
    public List<BigDecimal> getPreDataDayValuesById(Integer modelVersion, String startTime, String endTime){
        return preDataDayRepository.getPreDataDayValuesById(modelVersion,startTime,endTime);
    }

    /**
     * 开发环境下使用mock数据代替
     */
    private List<BigDecimal> getPreDataDayValueInDevEnv(int count) {
        //return mockDataUtil.buildDataList(count);
        return mockDataUtil.buildBigDecimalDataList(count);
    }

}
